package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.Cart;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;


@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Override
    public void addCart(Cart cart) {

        Long userId = UserContext.getUser().getId();
        String id = createId(userId,cart.getSkuId());


        //
        Optional<Cart> optional = this.cartRepository.findById(id);

        //有值
        if (optional.isPresent()){
            Cart storeCart = optional.get();
            cart.setNum(cart.getNum()+storeCart.getNum());
        }

        cart.setId(id);
        cart.setUserId(userId);
        cart.setUpdateTime(new Date());

        cartRepository.save(cart);
    }

    @Override
    public List<Cart> listCarts() {

        //TODO 再加入排序，根据updateTime 倒序排序
        return this.cartRepository.findByUserId(UserContext.getUser().getId());
    }

    @Override
    public void deleteBySkuId(Long skuId) {
        this.cartRepository.deleteById(createId(UserContext.getUser().getId(),skuId));

        //this.cartRepository.deleteBySkuIdAndUserId(skuId,UserContext.getUser().getId());
    }

    public String createId(Long userId,Long skuId){

        return String.format("u%ds%d",userId,skuId);
    }
}
